package com.bridgetree.jubaocrm.ui.project;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.JubaoCRMApplication;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.util.Interviews;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.project.XMChildDocumentationAdapter.SubmitComAsyc;
/**
 * 外出申请/交流记录 的 访谈
 */
@SuppressLint("SimpleDateFormat")
public class XMChildApplyRecordItemActivity extends Activity {
	private final String TAG = "XMChildCustomerContactActivity";

	private Interviews mInterviews;

	private Projects mProjects;

	private Context mContext;

	private TextView xm_ar_item_de_time = null;// 时间

	private TextView xm_ar_item_de_addressName = null;// 地点

	private TextView xm_ar_item_de_addressQiandao = null;// 签到

	private TextView xm_ar_item_de_cclxrName = null;// 客户联系人

	private TextView xm_ar_item_de_mecyName = null;// 我方参与人

	private TextView xm_ar_item_de_content = null;// 交流内容

	private Button bt_bl = null;

	private ImageView xm_ar_item_de_iv = null;

	private RelativeLayout xm_project_qd_RelativeLayout = null;

	private TextView xm_project_qd_quxiao = null;

	private TextView xm_project_qd_shenping = null;

	private TextView xm_project_qd_qiandao = null;

	private String where = "";

	private int index = -1;

	private int Pageindex = -1;

	private boolean isSinged = false;

	private boolean isRecord = false;

	private JubaoCRMApplication app;

	private double latitude = 0f;
	private double longitude = 0f;
	
	private String user_id =""; 
	private String token ="";

	// 定位相关
	private LocationClient mLocClient;

	// private LocationData locData;

	public MyLocationListenner myListener = new MyLocationListenner();

	// 地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
	// 如果不处理touch事件，则无需继承，直接使用MapView即可
	private MyLocationMapView mMapView; // 地图View
	private MapController mMapController;

	private ProgressDialog locationPd;
	// private GeoPoint newPoint;

	// // 定义地图引擎管理类
	// private BMapManager mapManager;
	// // 定义搜索服务类
	// private MKSearch mMKSearch;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/**
		 * 使用地图sdk前需先初始化BMapManager. BMapManager是全局的，可为多个MapView共用，它需要地图模块创建前创建，
		 * 并在地图地图模块销毁后销毁，只要还有地图模块在使用，BMapManager就不应该销毁
		 */
		app = (JubaoCRMApplication) this.getApplication();
		if (app.mBMapManager == null) {
			app.mBMapManager = new BMapManager(getApplicationContext());
			/**
			 * 如果BMapManager没有初始化则初始化BMapManager
			 */
			app.mBMapManager.init(JubaoCRMApplication.strKey,
					new JubaoCRMApplication.MyGeneralListener());
		}
		setContentView(R.layout.xm_apply_record_item_details);
		mContext = this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		index = -1;
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		TextView xm_arid_tv_title = (TextView) findViewById(R.id.xm_arid_tv_title);
		xm_ar_item_de_iv = (ImageView) findViewById(R.id.xm_ar_item_de_iv);
		xm_ar_item_de_time = (TextView) findViewById(R.id.xm_ar_item_de_time);
		xm_ar_item_de_addressName = (TextView) findViewById(R.id.xm_ar_item_de_addressName);
		xm_ar_item_de_addressQiandao = (TextView) findViewById(R.id.xm_ar_item_de_addressQiandao);
		xm_ar_item_de_cclxrName = (TextView) findViewById(R.id.xm_ar_item_de_cclxrName);
		xm_ar_item_de_mecyName = (TextView) findViewById(R.id.xm_ar_item_de_mecyName);
		xm_ar_item_de_content = (TextView) findViewById(R.id.xm_ar_item_de_content);
		xm_project_qd_RelativeLayout = (RelativeLayout) findViewById(R.id.xm_project_qd_RelativeLayout);
		xm_project_qd_quxiao = (TextView) findViewById(R.id.xm_project_qd_quxiao);
		xm_project_qd_shenping = (TextView) findViewById(R.id.xm_project_qd_shenping);
		xm_project_qd_qiandao = (TextView) findViewById(R.id.xm_project_qd_qiandao);
		bt_bl = (Button) findViewById(R.id.bt_bl);
		xm_project_qd_RelativeLayout.setVisibility(View.GONE);

		if (intent.getExtras() != null) {
			Pageindex = intent.getExtras().getInt("index");
			mInterviews = (Interviews) intent.getExtras().getSerializable(
					"Interviews");
			mProjects = (Projects) intent.getExtras().getSerializable(
					"mProjects");
			xm_arid_tv_title.setText("访谈（" + mInterviews.getPeople_of_us()
					+ "）");
			xm_ar_item_de_time.setText(mInterviews.getTime_line());
			xm_ar_item_de_addressName.setText(mInterviews.getAddress());
			xm_ar_item_de_addressQiandao.setText("已在"
					+ mInterviews.getSigned_where() + "签到");
			xm_ar_item_de_cclxrName.setText(mInterviews.getPeople_of_client());
			xm_ar_item_de_mecyName.setText(mInterviews.getPeople_of_us());
			xm_ar_item_de_content.setText(mInterviews.getContent());
			String signedTime = mInterviews.getSigned_time();
			xm_ar_item_de_iv.setImageResource(R.drawable.check2x);
			if (signedTime == null || signedTime.trim().length() == 0) {
				xm_ar_item_de_addressQiandao.setText("未签到");
			} else {
				xm_ar_item_de_addressQiandao.setText("已在"
						+ mInterviews.getSigned_where() + "签到");
			}
			if (mInterviews.getContent() == null
					|| mInterviews.getContent().equals("")) {
				bt_bl.setVisibility(View.VISIBLE);
			} else {
				bt_bl.setVisibility(View.GONE);
			}

			if (mInterviews.getInterview_type().equals("面谈")) {
				xm_ar_item_de_iv.setVisibility(View.VISIBLE);
			} else {
				xm_ar_item_de_iv.setVisibility(View.GONE);
			}
		}

		findViewById(R.id.xm_arid_iv_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent();
						intent.putExtra("address", where);
						intent.putExtra("editTime", getNows());
						intent.putExtra("index", Pageindex);
						intent.putExtra("record",
								xm_ar_item_de_content.getText());
						if (isSinged && isRecord) {
							// 签到和补录
							setResult(0x0001, intent);
						} else {
							if (isRecord) {
								// 只补录
								setResult(0x0002, intent);
							} else if (isSinged) {
								// 只签到
								setResult(0x0003, intent);
							}
						}
						finish();
					}
				});

		findViewById(R.id.xm_ar_item_de_iv).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (mInterviews != null ) {
							Log.d(TAG, "where:"+where);
							if(where==null || where.equals("")){
								showLocationProgressDialog();
							}else{
								showSignDialog(false);
							}
						}
					}
				});

		bt_bl.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = null;
				Bundle bundle = null;
				intent = new Intent(mContext, XMChildBuLuActivity.class);
				bundle = new Bundle();
				bundle.putSerializable("Interviews", mInterviews);
				bundle.putSerializable("mProjects", mProjects);
				intent.putExtras(bundle);
				XMChildApplyRecordItemActivity.this.startActivityForResult(
						intent, 1000);
			}
		});

		// // 地图初始化
		mMapView = (MyLocationMapView) findViewById(R.id.bmapsView);
		mMapController = mMapView.getController();
		mMapView.getController().setZoom(20);
		// 03-25 15:57:41.237: E/定位(3633): latitude = 34.202432 //longitude =
		// 108.894576
		mMapView.getController()
				.setCenter(
						new GeoPoint((int) (34.202432 * 1e6),
								(int) (108.894576 * 1e6)));
		mMapView.getController().enableClick(true);
		mMapView.setBuiltInZoomControls(false);

		// 定位初始化
		mLocClient = new LocationClient(this);
		// locData = new LocationData();
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("gcj02"); // 设置坐标类型为高德,和服务端统一
		option.setScanSpan(3000);
		option.setAddrType("all");
		mLocClient.setLocOption(option);
		mLocClient.start();
	}
	private void showLocationProgressDialog() {
		locationPd = new ProgressDialog(this);
		locationPd.setMessage("loading..");
		locationPd.setIndeterminate(true);
		locationPd.setCancelable(true);
		locationPd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		locationPd.setButton("cancle", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		locationPd.show();
	}
	
	private void showSignDialog(boolean isWaiting) {
		//如果定位正在等待，去掉loading框
		if(isWaiting){
			if(locationPd!=null && locationPd.isShowing()){
				locationPd.dismiss();
				executeShowSignDialog();
			}
		}else{
			executeShowSignDialog();
		}
	}
	private void executeShowSignDialog() {
		// 1，定位
		xm_project_qd_shenping.setText("您现在的位置：" + where);
		// 2，
		xm_project_qd_RelativeLayout
				.setVisibility(View.VISIBLE);

		xm_project_qd_quxiao = (TextView) findViewById(R.id.xm_project_qd_quxiao);
		xm_project_qd_shenping = (TextView) findViewById(R.id.xm_project_qd_shenping);
		xm_project_qd_qiandao = (TextView) findViewById(R.id.xm_project_qd_qiandao);

		xm_project_qd_RelativeLayout
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						xm_project_qd_RelativeLayout
								.setVisibility(View.GONE);
					}
				});
		xm_project_qd_quxiao
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						xm_project_qd_RelativeLayout
								.setVisibility(View.GONE);
					}
				});
		xm_project_qd_qiandao
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						xm_project_qd_RelativeLayout
								.setVisibility(View.GONE);
						getApplyRecordData();
					}
				});
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!xm_ar_item_de_content.getText().toString().equals("")) {
			bt_bl.setVisibility(View.GONE);
		}
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			double radius = location.getRadius();
			if(location.getAddrStr()!=null){
				where = location.getAddrStr();
				latitude = location.getLatitude();
				longitude = location.getLongitude();
				showSignDialog(true);
			}
			Log.e("定位", "latitude =  " + latitude + " //longitude =  "
					+ longitude + "   //   radius  =  " + radius
					+ "   //  where   =  " + where);
			// latitude = 34.20921 //longitude = 108.875167 // radius =
			// 77.8730239868164 // where = 陕西省西安市雁塔区丈八四路

			// System.out.println("0" + location.getStreet());
			// System.out.println("1" + location.getStreetNumber());
			// System.out.println("2" + location.getAddrStr());
			// System.out.println("3" + location.getAltitude());
			// System.out.println("4" + location.getCity());
			// System.out.println("5" + location.getCityCode());
			// System.out.println("6" + location.getCoorType());
			// System.out.println("7" + location.getDerect());
			// System.out.println("8" + location.getDistrict());
			// System.out.println("9" + location.getProvince());
			// System.out.println("10" + location.getSatelliteNumber());
			// System.out.println("11" + location.getSpeed());
			// newPoint = new GeoPoint((int) (location.getLatitude() * 1E6),
			// (int) (location.getLongitude() * 1E6));
			if (xm_project_qd_shenping != null) {
				xm_project_qd_shenping.setText("您现在的位置：" + where);
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1000 && data != null) {
			String record = data.getStringExtra("record");
			xm_ar_item_de_content.setText(record);
			isRecord = true;
		}
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if (content != null && content.trim().equals("用户不存在")) {
							// finish();
						}
						if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
							LoginUtil.executeLoginFaild(mContext);
						}

					}
				}).show();
	}

	public String getNows() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	private void getApplyRecordData() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			// String URL =
			// "http://crmsoap.woniuwo.cn/interviews?project_id="+mProjects.getProject_id()
			// +"&user_id="+mProjects.getUser_id()+"&token="+mProjects.getToken()+"&validation="
			// +CRMUserBaseInfo.kValication+"&page="+pageIndex;
			// String URL =
			// "http://crmsoap.woniuwo.cn/sign?iid="+mInterviews.getInterview_id()
			// +"&user_id="+mProjects.getUser_id()+"&token="+mProjects.getToken()
			// +"&validation="+CRMUserBaseInfo.kValication+"&latitude="+mInterviews.getLatitude()
			// +"&longitude="+mInterviews.getLongitude()+"&signed_where="+mInterviews.getSigned_where();

			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");
			// RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			// JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
			// Request.Method.GET, URL, null, new
			// Response.Listener<JSONObject>() {
			// @Override
			// public void onResponse(JSONObject response) {
			// System.out.println("签到  response="+response);
			// if (progressDialog.isShowing()&&progressDialog!=null) {
			// progressDialog.dismiss();
			// }
			// try {
			// if (!response.isNull("errors")) {
			// String errors = response.get("errors").toString();
			// if (errors.equals("[]")) {
			// } else {
			// org.json.JSONArray jsonArr;
			// if (!response.isNull("errors")) {
			// LoginError mLoginError = new LoginError();
			// jsonArr = response.getJSONArray("errors");
			// if (jsonArr.length() > 0) {
			// for (int i = 0; i < jsonArr.length(); i++) {
			// JSONObject jsonObj2 = jsonArr.getJSONObject(i);
			// if (!jsonObj2.isNull("desc")) {
			// String desc = jsonObj2.getString("desc");
			// mLoginError.setDesc(desc);
			// }
			// if (!jsonObj2.isNull("value")) {
			// String value = jsonObj2.getString("value");
			// mLoginError.setValue(value);
			// }
			// }
			// }
			// }
			// }
			// }
			// } catch (NumberFormatException e) {
			// e.printStackTrace();
			// } catch (JSONException e) {
			// e.printStackTrace();
			// }
			//
			// }
			// },
			// new Response.ErrorListener() {
			// @Override
			// public void onErrorResponse(VolleyError arg0) {
			// System.out.println("sorry,Error");
			// }
			// });
			// requestQueue.add(jsonObjectRequest);

			// String URL =
			// "http://crmsoap.woniuwo.cn/sign?iid="+mInterviews.getInterview_id()
			// +"&user_id="+mProjects.getUser_id()+"&token="+mProjects.getToken()
			// +"&validation="+CRMUserBaseInfo.kValication+"&latitude="+mInterviews.getLatitude()
			// +"&longitude="+mInterviews.getLongitude()+"&signed_where="+mInterviews.getSigned_where();
			//
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("iid", mInterviews.getInterview_id());
			mMap.put("user_id", user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			mMap.put("latitude", latitude + "");
			mMap.put("longitude", longitude + "");
			mMap.put("signed_where", where);

			String URL = Network.API_DOMAIN + "/sign?";
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							System.out.println("签到  response=" + response);
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
											.toString();
									if (errors.equals("[]")) {
										xm_ar_item_de_iv
												.setVisibility(View.GONE);
										xm_ar_item_de_addressQiandao
												.setText("已在" + where + "签到");
										isSinged = true;
										index = Pageindex;
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
													.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
														.length(); i++) {
													JSONObject jsonObj2 = jsonArr
															.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
																.getString("desc");
														mLoginError
																.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
																.getString("value");
														mLoginError
																.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		if (mLocClient != null) {
			mLocClient.stop();
		}
		mMapView.destroy();
		super.onDestroy();
	}

}

/**
 * 继承MapView重写onTouchEvent实现泡泡处理操作
 * 
 * @author hejin
 */
class MyLocationMapView extends MapView {

	public MyLocationMapView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public MyLocationMapView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MyLocationMapView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return true;
	}

}
